// ui/helpers.go
package ui

import (
	"device_manager/models"
	"device_manager/utils"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"time"

	"gorm.io/gorm"
)

func loadDevices(db *gorm.DB, deviceType string) []models.Device {
	var devices []models.Device
	db.Where("device_type = ?", deviceType).Find(&devices)
	return devices
}

func logAction(db *gorm.DB, deviceID uint, action, result string) {
	log := models.Log{
		DeviceID: deviceID,
		Action:   action,
		Result:   result,
	}
	if err := db.Create(&log).Error; err != nil {
		utils.ShowError(err)
	}
}
func showDeviceLogs(db *gorm.DB, device *models.Device) {
	var logs []models.Log
	db.Where("device_id = ?", device.ID).Order("created_at desc").Find(&logs)

	logList := widget.NewList(
		func() int { return len(logs) },
		func() fyne.CanvasObject {
			return widget.NewLabel("")
		},
		func(i widget.ListItemID, o fyne.CanvasObject) {
			logEntry := logs[i]
			o.(*widget.Label).SetText(fmt.Sprintf("%s - %s - %s", logEntry.CreatedAt.Format(time.RFC3339), logEntry.Action, logEntry.Result))
		},
	)

	w := fyne.CurrentApp().NewWindow(fmt.Sprintf("设备 %s 的日志", device.Name))
	w.SetContent(container.NewBorder(nil, nil, nil, nil, logList))
	w.Resize(fyne.NewSize(600, 400))
	w.Show()
}
